<template>
  <n-modal
    v-model:show="getProps.modalData.show"
    class="custom-card"
    preset="card"
    :style="{ width: '900px' }"
    :bordered="false"
    :segmented="{
      content: true,
      footer: true
    }"
    :mask-closable="false"
  >
    <template #header>
      <div>批量修改投放日期</div>
      <n-text style="font-size: 14px">已选{{ getProps.modalData?.adgroupIdList?.length }}个广告</n-text>
    </template>
    <n-space vertical>
      <n-radio-group v-model:value="form.type">
        <n-radio key="统一修改" :value="1">统一修改</n-radio>
        <n-radio key="分别修改" :value="2">分别修改</n-radio>
      </n-radio-group>
      <n-data-table
        ref="tableRef"
        size="small"
        :data="getProps.modalData.checkedData"
        :columns="columns"
        :row-key="(row) => row.id"
        row-class-name="text-sm"
        max-height="infinite"
      />
      <n-space justify="end">
        <x-button @click="handleCancel">取消</x-button>
        <x-button :loading="loading" type="primary" @click="handleSave">确定</x-button>
      </n-space>
    </n-space>
  </n-modal>
</template>

<script setup lang="ts">
  import { computed, h, onMounted, reactive, ref, watch } from 'vue'
  import { XButton, XForm } from '@/components'

  import {
    NModal,
    NSpace,
    NInputNumber,
    NRadioGroup,
    NRadio,
    useMessage,
    NSwitch,
    NText,
    NDataTable,
    NDatePicker
  } from 'naive-ui'
  import { useStore } from '@/store'
  import { useRoute } from 'vue-router'
  import { defineProps, defineEmits } from 'vue'
  import { formatDate } from '@/utils'
  import { gdtBatchDate } from '@/api/intelligent'
  const route = useRoute()
  const emit = defineEmits(['success'])
  const message = useMessage()
  const store = useStore()
  const accountCode = computed(() => {
    return route.query.accountCode
  })
  const loading = ref(false)
  const props = defineProps({
    modalData: {
      type: Object,
      default: () => ({})
    }
  })
  const getProps = reactive(props)
  const form = ref({
    accountCode: route.query.accountCode,
    type: 1
  })
  const today = new Date()
  const maxDate = new Date(today)
  maxDate.setFullYear(today.getFullYear() + 1)
  const disablePreviousDate = (ts) => {
    return ts + 60 * 60 * 24 * 1000 < Date.now() || ts > maxDate
  }
  const columns = computed(() => {
    const arr = [
      {
        title: '广告名称',
        key: 'accountName',
        width: 100,
        render(row: any) {
          return h(NSpace, { vertical: true }, () => [h(NText, {}, () => row.adgroupName)])
        }
      },
      {
        title: '原投放日期',
        key: 'launchTime',
        width: 100
      },
      form.value.type === 2
        ? {
            title: '修改投放日期',
            key: 'configuredStatus',
            width: 100,
            render(row: any) {
              return h(NSpace, { vertical: true }, () => [
                h(NDatePicker, {
                  type: 'daterange',
                  value: row.dateRange,
                  onUpdateValue(v: number) {
                    row.dateRange = v
                  },
                  isDateDisabled: disablePreviousDate
                })
              ])
            }
          }
        : {
            title: '修改投放日期',
            key: 'configuredStatus',
            rowSpan: (rowData: any, rowIndex: number) => (rowIndex === 0 ? getProps.modalData.checkedData.length : 1),
            width: 100,
            render(row: any) {
              return h(NSpace, { vertical: true }, () => [
                h(NDatePicker, {
                  type: 'daterange',
                  value: row.dateRange,
                  onUpdateValue(v: number) {
                    row.dateRange = v
                  },
                  isDateDisabled: disablePreviousDate
                })
              ])
            }
          }
    ]
    return arr
  })
  onMounted(() => {})
  async function handleSave() {
    const checkedData = getProps.modalData.checkedData
    const adgroupList: { accountCode: any; outAdgroupId: any; configuredStatus: string; bidAmount: number }[] = []
    checkedData.forEach((item: any) => {
      adgroupList.push({
        accountCode: item.accountCode,
        outAdgroupId: item.adgroupId,
        beginDate:
          form.value.type === 1
            ? checkedData?.[0]?.dateRange
              ? formatDate(checkedData?.[0]?.dateRange[0])
              : null
            : item.dateRange?.[0]
            ? formatDate(item.dateRange[0])
            : null,
        endDate:
          form.value.type === 1
            ? checkedData?.[0]?.dateRange
              ? formatDate(checkedData?.[0]?.dateRange[1])
              : null
            : item.dateRange?.[1]
            ? formatDate(item.dateRange[1])
            : null
      })
    })
    const params = {
      adgroupList: adgroupList
    }
    loading.value = true
    store
      .dispatch('intelligent/gdtBatchDate', params)
      .then((res) => {
        message.success(`${res.data.successNum}个广告修改成功`)
        loading.value = false

        emit('success')
        getProps.modalData.show = false
      })
      .catch(() => {
        loading.value = false
      })
  }
  function handleCancel() {
    getProps.modalData.show = false
  }
</script>

<style scoped lang="scss">
  .tips {
    margin-top: 20px;
  }
  .max-cost {
    padding: 10px 0;
    text-align: center;
  }
</style>
